import jwt from 'jsonwebtoken'
import db from '../db/database.js'

export function authenticateToken(req, res, next) {
  const authHeader = req.headers['authorization']
  const token = authHeader && authHeader.split(' ')[1]

  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '未提供认证令牌',
      success: false
    })
  }

  try {
    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key')
    req.user = decoded
    next()
  } catch (error) {
    return res.status(403).json({
      code: 403,
      message: '无效的认证令牌',
      success: false
    })
  }
}

// Socket.IO 认证函数
export async function authenticateSocket(token) {
  try {
    if (!token) {
      return null
    }

    const decoded = jwt.verify(token, process.env.JWT_SECRET || 'your-secret-key')
    const user = db.prepare('SELECT id, username FROM users WHERE id = ?').get(decoded.userId)
    
    if (!user) {
      return null
    }

    return {
      userId: user.id,
      username: user.username
    }
  } catch (error) {
    return null
  }
}

